package cn.wqk.demo.interceptor;

import cn.wqk.demo.utils.JWTUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: 吴青珂
 * @Date: 2020/12/25/13:17
 * @Description: JWT过滤器
 */
public class JWTInterceptor implements HandlerInterceptor {

    /**
     *  拦截器验证token，验证成功放行，否则不放行并且在response里塞入状态和错误信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token"); // 从request请求头中获取token
        HashMap<String, Object> returnMap = new HashMap<>(); //初始化返回给前端的map
        try {
            JWTUtils.getTokenInfo(token); //token验证
            return true; //token验证通过过滤器放行
        } catch (SignatureVerificationException e) { //签名不一致
            returnMap.put("msg","签名不一致");
        } catch (TokenExpiredException e) {  //token已过期
            returnMap.put("msg","token已过期");
        } catch (AlgorithmMismatchException e) { //算法不匹配
            returnMap.put("msg","算法不匹配");
        } catch (InvalidClaimException e) { // payload已失效
            returnMap.put("msg","payload已失效");
        }
        returnMap.put("status",false);
        String json = new ObjectMapper().writeValueAsString(returnMap); //利用jackson将map转为json
        response.setContentType("application/json;charset=utf-8");  //设置response响应格式
        response.getWriter().println(json); //将json塞进response里
        return false;
    }
}
